package com.tanhua.server.service.impl;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.mongo.CommonLikeUser;
import com.tanhua.model.vo.CommonLikeUserVO;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.intercepter.UserThreadLocal;
import com.tanhua.server.service.UserInfoService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    /**
     * 保存用户信息
     *
     * @param userInfo
     */
    @Override
    public void loginRegInfo(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 上传头像
     */
    @Override
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1.将图片上传到阿里云
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(upload);
        if (!detect) {
            //2.1不包含人脸
            throw new BusinessException(ErrorResult.faceError());
        } else {
            //2.2包含人脸时,调用api接口更新数据
            //封装数据到userInfo
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(upload);
            //调用方法
            userInfoApi.update(userInfo);
        }
    }


    /**
     * 查询用户或自己详情信息
     *
     * @param id
     * @return
     */
    @Override
    public UserInfoVo findById(Long id) {
        UserInfo byId = userInfoApi.findById(id);
        UserInfoVo vo = new UserInfoVo();

        //copy相同属性
        BeanUtils.copyProperties(byId, vo);

        //年龄原本是Int vo是string
        if (byId.getAge() != null) {
            vo.setAge(byId.getAge().toString());
        }
        return vo;
    }

    /**
     * 修改信息
     *
     * @param userInfo
     */
    @Override
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    /**
     * 查询列表
     *
     * @param type     查询的类型
     *                 1 相互喜欢
     *                 2 喜欢的
     *                 3 粉丝
     *                 4 访客
     * @param page     页码
     * @param pagesize 查询几条
     * @param nickname 昵称
     */
    @Override
    public ResponseEntity queryLikeList(Integer type, Integer page, Integer pagesize, String nickname) {

        PageResult<CommonLikeUser> pageResult = null;
        if (type == 1) {
            //分页查询 当前用户相互喜欢的列表：查询tanhua_users好友表，Friend==>本质是需要好友的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.queryFriendsList(UserThreadLocal.getUserId(), page, pagesize);
        } else if (type == 2) {
            //分页查询 当前用户喜欢的 列表：查询user_like单向喜欢表，UserLike==>本质是需要对方的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.queryLikeList(UserThreadLocal.getUserId(), page, pagesize);
        } else if (type == 3) {
            //分页查询 喜欢当前用户的 列表：查询user_like单向喜欢表，UserLike==>本质是需要对方的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.queryFansList(UserThreadLocal.getUserId(), page, pagesize);
        } else if (type == 4) {
            //分页查询  当前用户的访客列表：查询visitors访客表，Visitor==>本质是需要访客的id，缘分值 CommonLikeUser
            pageResult = userLikeApi.findVisitorList(UserThreadLocal.getUserId(), page, pagesize);
        }
        //获取Items数据
        List<CommonLikeUser> commonLikeUserList = pageResult.getItems();
        //转换成VO对象
        List<CommonLikeUserVO> voList = new ArrayList<>();
        for (CommonLikeUser commonLikeUser : commonLikeUserList) {
            CommonLikeUserVO vo = new CommonLikeUserVO();
            //查询对方的用户详情
            UserInfo userInfo = userInfoApi.findById(commonLikeUser.getTargetUserId());
            BeanUtils.copyProperties(userInfo, vo);

            //设置缘分值
            vo.setMatchRate(commonLikeUser.getScore().intValue());
            //设置是否喜欢此用户
            vo.setAlreadyLove(false);

            voList.add(vo);
        }
        //构造返回值
        PageResult<CommonLikeUserVO> result = new PageResult<>();
        BeanUtils.copyProperties(pageResult, result);
        result.setItems(voList);

        return ResponseEntity.ok(result);
    }

    /**
     * 粉丝-喜欢。对某个粉丝点击了“喜欢”
     *
     * @param targetUserId 粉丝id
     */
    public ResponseEntity likeFans(Long targetUserId) {
        /**
         * 喜欢也是粉丝
         */
       /* //1. 删除单向的喜欢 targetId喜欢当前用户
        userLikeApi.delete(targetUserId, UserThreadLocal.getUserId());*/

        //2. 建立双向的好友关系
        friendApi.addFriend(targetUserId, UserThreadLocal.getUserId());

        //3. 把好友关系注册到环信。注意：好友双方都必须已经在环信注册过，否则好友关系添加失败
        huanXinTemplate.addContact(UserThreadLocal.getUserId().toString(), targetUserId.toString());

        return ResponseEntity.ok(null);
    }

    /**
     * 取消喜欢
     *
     * @param targetUserId 要取消的用户id
     * @return
     */
    public ResponseEntity removeLike(Long targetUserId) {

        //1.查询是否是好友,
        Boolean flag = friendApi.findFriend(UserThreadLocal.getUserId(), targetUserId);

        if (flag) {
            //1.1是,先删除好友表的关系
            friendApi.deleteFriend(UserThreadLocal.getUserId(), targetUserId);
        }

        //2.删除我的单项喜欢的用户
        userLikeApi.delete(UserThreadLocal.getUserId(), targetUserId);

        return ResponseEntity.ok(null);
    }
}